package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.OnDutySalarySetMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.EmployeeExt;
import com.ruan.pojoExt.ResignExt;
import com.ruan.pojoExt.SalaryExt;
import com.ruan.pojoExt.SalarySetExt;
import com.ruan.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/salary")
@CrossOrigin
public class SalaryController {


    @Autowired
    private SalaryService salaryService;

    @Autowired
    private OnDutySalarySetMapper onDutySalarySetMapper;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OnDutySalarySetService onDutySalarySetService;

    @Autowired
    private SalarySetService salarySetService;

    @Autowired
    PositionService positionService;

//    @PostMapping("/getSalaryList/{currentPage}/{pageSize}")
//    public Result getSalaryList(@PathVariable int currentPage,
//                                @PathVariable int pageSize,
//                                @RequestBody LTOQueryCondition LtoQueryCondition){
//
//        IPage<Salary> iPage = salaryService.getSalaryList(currentPage, pageSize, LtoQueryCondition);
//        if (iPage!=null){
//            return new Result(Code.SELECT_OK,iPage);
//        }
//        return new Result(Code.SELECT_ERR,"员工工资发放列表查询失败！");
//    }
    /**
     * 获取薪资详情列表
     * @param currentPage 当前页
     * @param pageSize 每页最大数
     * @param ltoQueryCondition 查询条件
     * @return
     */
    @PostMapping("/getSalaryList/{currentPage}/{pageSize}")
    public Result getSalaryList(@PathVariable int currentPage,
                                @PathVariable int pageSize,
                                @RequestBody LTOQueryCondition ltoQueryCondition) {
//        System.out.println("getSalaryList传来的参数是："+ltoQueryCondition);
        Date month = ltoQueryCondition.getMonth();//2024-2-1
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String monthStr = sdf.format(month);
//        System.out.println("工资月份为->>>"+monthStr);
        LambdaQueryWrapper<Salary> queryWrapper =new LambdaQueryWrapper<>();
        //------------------------------------------------
        LambdaQueryWrapper<Employee> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.like(ltoQueryCondition.getName()!=null,Employee::getName,ltoQueryCondition.getName());
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);
        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
//        wrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句
        queryWrapper.in(ltoQueryCondition.getName()!=null,
                Salary::getEmployeeId, employeeIds);

        queryWrapper.eq(ltoQueryCondition.getDepartmentId()!=null,
                Salary::getDepartmentId,ltoQueryCondition.getDepartmentId());
//        System.out.println("到哪了");
//        queryWrapper.like(ltoQueryCondition.getName()!=null,Salary::getName,ltoQueryCondition.getName());
        queryWrapper.like(Salary::getMonth,monthStr);

        Page<Salary> iPage = new Page<>(currentPage,pageSize);

        Page<SalaryExt> iPageExt=new Page<>();//封装

        salaryService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询

        BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
        List<Salary> records = iPage.getRecords();
        List<SalaryExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
            SalaryExt salaryExt = new SalaryExt();//只有ResignExt符合项目管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,salaryExt);//先填充入Resign的普通属性

            Long departmentId = item.getDepartmentId();//拿到了每个员工所对应的部门id
            Long employeeId = item.getEmployeeId();

            Employee employee = employeeMapper.selectById(employeeId);
            Department department = departmentService.getById(departmentId);
            if(employee != null){//能查到员工
                salaryExt.setEmployeeName(employee.getName());
                salaryExt.setPhone(employee.getPhone());
            }
            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                salaryExt.setPosition(position.getPname());
            }
            if(department != null){//能查到员工的部门
                String departmentName = department.getName();
                salaryExt.setDepartmentName(departmentName);//填充入employee没有的employeeName属性
            }
            return salaryExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
        }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
//        System.out.println("list里有了什么"+list);//.toString()
        iPageExt.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性
//        return R.success(iPageExt);

        return new Result(Code.SELECT_OK,iPageExt);
//        return salaryMapper.selectPage(iPage, queryWrapper);

    }

//    @PostMapping("/getSalarySet/{currentPage}/{pageSize}")
//    public Result getSalarySet(@PathVariable int currentPage,
//                               @PathVariable int pageSize,
//                               @RequestBody LTOQueryCondition LtoQueryCondition){
//
////        List<SalarySet> salarySetList = salarySetService.getSalarySet(currentPage, pageSize, LtoQueryCondition);
//        IPage<SalarySet> iPage = salarySetService.getSalarySet(currentPage, pageSize, LtoQueryCondition);
//        if (iPage!=null){
//            return new Result(Code.SELECT_OK,iPage);
//        }
//        return new Result(Code.SELECT_ERR,"员工工资设置列表查询失败！");
//    }
    /**
     * 获取员工薪资设置列表
     * @param currentPage 当前页
     * @param pageSize 每页最大数
     * @param ltoQueryCondition 查询条件
     * @return
     */
    @PostMapping("/getSalarySet/{currentPage}/{pageSize}")
    public Result getSalarySet(@PathVariable int currentPage,
                               @PathVariable int pageSize,
                               @RequestBody LTOQueryCondition ltoQueryCondition) {

        LambdaQueryWrapper<SalarySet> queryWrapper =new LambdaQueryWrapper<>();
        //按员工名搜索
        LambdaQueryWrapper<Employee> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.like(ltoQueryCondition.getName()!=null,
                Employee::getName,ltoQueryCondition.getName());
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);
        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
//        wrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句
        queryWrapper.in(ltoQueryCondition.getName()!=null,
                SalarySet::getEmployeeId, employeeIds);
        //按部门名搜索
        queryWrapper.eq(ltoQueryCondition.getDepartmentId()!=null,
                SalarySet::getDepartmentId,ltoQueryCondition.getDepartmentId());

        LambdaQueryWrapper<Employee> EmployeeQueryWrapper = new LambdaQueryWrapper<>();
        //调薪需要除开离职和待审核的员工
        EmployeeQueryWrapper.ne(Employee::getStatus,"离职");
        EmployeeQueryWrapper.ne(Employee::getStatus,"待审核");
        //要发工资的人，才能调薪
        List<Employee> employeeList1 = employeeMapper.selectList(EmployeeQueryWrapper);
        List<Long> employeeIds1 = employeeList1.stream().map(Employee::getId).collect(Collectors.toList());
        queryWrapper.in(SalarySet::getEmployeeId, employeeIds1);


        Page<SalarySet> iPage = new Page<>(currentPage,pageSize);
        Page<SalarySetExt> iPageExt=new Page<>();//封装

        salarySetService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询
        BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
        List<SalarySet> records = iPage.getRecords();
        List<SalarySetExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
            SalarySetExt salarySetExt = new SalarySetExt();//只有EmployeeExt符合项目管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,salarySetExt);//先填充入employee的普通属性

            Long departmentId = item.getDepartmentId();//拿到了每个员工所对应的部门id
            Long employeeId = item.getEmployeeId();
            Employee employee = employeeMapper.selectById(employeeId);
            Department department = departmentService.getById(departmentId);

            if(employee != null){//能查到员工
                salarySetExt.setEmployeeName(employee.getName());
                salarySetExt.setPhone(employee.getPhone());
            }
            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                salarySetExt.setPosition(position.getPname());
            }
            if(department != null){//能查到员工的部门
                String departmentName = department.getName();
                salarySetExt.setDepartmentName(departmentName);//填充入employee没有的employeeName属性
            }
            return salarySetExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
        }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list
        System.out.println("list里有了什么"+list);//.toString()
        iPageExt.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性
//        return R.success(iPageExt);
//        return salarySetMapper.selectPage(iPage, queryWrapper);
        return new Result(Code.SELECT_OK,iPageExt);
    }


    @PutMapping("/setSalary/{id}/{adminId}")
    public Result setSalary(@PathVariable Integer id,@PathVariable Integer adminId,@RequestBody SalarySet salarySet){

        try {
            salarySetService.setSalary(id,adminId,salarySet);
            return new Result(Code.UPDATE_OK,"员工工资设置成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"员工工资设置失败！");
        }
    }

    @PostMapping("/addSalarySet/{adminId}/{userId}")
    public Result addSalarySet(@PathVariable Integer adminId,
                               @PathVariable Integer userId,
                               @RequestBody SalarySet salarySet){
        try {
            salarySetService.addSalarySet(adminId,userId,salarySet);
            return new Result(Code.SAVE_OK,"员工工资设置成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERR,"员工工资设置失败！");
        }
    }

    @GetMapping("/getOnDutySalarySet")
    public Result getOnDutySalarySet(){

        OnDutySalarySet onDutySalarySet = onDutySalarySetService.getOnDutySalarySet();
        if (onDutySalarySet!=null){
            return new Result(Code.SELECT_OK,onDutySalarySet);
        }else {
            return new Result(Code.SELECT_ERR,"获取考勤奖惩设置失败！");
        }
    }

    //设置请假扣除多少，加班补助多少。。。。
    @PutMapping("/setOnDutySalary")
    public Result setOnDutySalary(@RequestBody OnDutySalarySet onDutySalarySet){
        try {
//            onDutySalarySetService.setOnDutySalary(onDutySalarySet);
            onDutySalarySetMapper.updateById(onDutySalarySet);
            return new Result(Code.UPDATE_OK,"考勤奖惩设置成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"考勤奖惩设置失败！");
        }
    }

    @PutMapping("/payWages/{id}/{adminId}")
    public Result payWages(@PathVariable Integer id,@PathVariable Integer adminId){
        System.out.println("payWages传来的参数："+id+adminId);
        try {
            salaryService.payWages(id,adminId);
            return new Result(Code.UPDATE_OK,"薪资发放成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"薪资发放失败！");
        }
    }

    @PostMapping("/getSelfSalary/{currentPage}/{pageSize}")
    public Result getSelfSalary(@PathVariable int currentPage,
                                @PathVariable int pageSize,
                                @RequestBody QuerySelfAttendanceCondition querySelfAttendanceCondition){

        IPage<Salary> iPage = salaryService.getSelfSalary(currentPage,pageSize, querySelfAttendanceCondition);

        if (iPage!=null){
            return new Result(Code.SELECT_OK,iPage);
        }
        return new Result(Code.SELECT_ERR,"查询个人薪资记录失败！");

    }

    @GetMapping("/getSelfSalarySet")
    public Result getSelfSalarySet(String phone){
        SalarySetExt salarySetExt = salarySetService.getSelfSalarySet(phone);
        if (salarySetExt!=null){
            return new Result(Code.SELECT_OK,salarySetExt);
        }else {
            return new Result(Code.SELECT_ERR,"查询个人薪资失败！");
        }
    }
}
